package com.sxj.corejava.code02_jdbc;

import com.sxj.corejava.entity.User;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

/**
 * @author 石小俊
 * @date 2023年11月2023/11/30日 18:20
 */
public class Test03_CURD操作 {
    public static void main(String[] args) {
        User user = new User("wangwu","111111","13912345678","江苏-南京");
        insertUser(user);
//        User user = new User(4,"jack","222222","13912345678","江苏-南京");
//        updateUser(user);
//        deleteById(4);
//        List<User> users = selectAll();
//        for(User user : users){
//            System.out.println(user);
//        }

//        User user = selectById(1);
//        System.out.println(user);

    }


    /**
     * 将参数指定的User对象的数据插入到数据库的t_user表中
     * 对象的属性值即为插入到数据库中的字段的值
     * 对象的属性与数据库字段一一对应
     * 类映射表
     * 属性映射字段
     * @param user
     */
    public static void insertUser(User user) {
        Connection conn = null;
        PreparedStatement ps = null;
        try {
            Class.forName("com.mysql.jdbc.Driver");
            conn = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/jdbc?useUnicode=true&characterEncoding=utf-8", "root", "");
            String sql = new StringBuffer()
                    .append(" insert into ")
                    .append(" t_user ")
                    .append("   (username,password,phone,address)")
                    .append(" values ")
                    .append("   (?,?,?,?)")
                    .toString();
            ps = conn.prepareStatement(sql);
            ps.setString(1,user.getUsername());
            ps.setString(2,user.getPassword());
            ps.setString(3,user.getPhone());
            ps.setString(4,user.getAddress());
            int rows = ps.executeUpdate();
            System.out.println("Query OK, " + rows + " rows affected");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
            System.out.println("未找到驱动");
        } catch (SQLException e) {
            e.printStackTrace();
            System.out.println("连接数据库失败");
        } finally {
            // 6.释放资源
            if (conn != null) {
                try {
                    conn.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                    System.out.println("释放连接出错");
                }
            }
            if (ps != null) {
                try {
                    ps.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public static void updateUser(User user){
        Connection conn = null;
        PreparedStatement ps = null;
        try {
            Class.forName("com.mysql.jdbc.Driver");
            conn = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/jdbc?useUnicode=true&characterEncoding=utf-8", "root", "");

            String sql = new StringBuffer()
                    .append(" update t_user ")
                    .append(" set ")
                    .append("   username = ?, ")
                    .append("   password = ?, ")
                    .append("   phone = ?, ")
                    .append("   address = ? ")
                    .append(" where id = ? ")
                    .toString();
            ps = conn.prepareStatement(sql);
            ps.setString(1,user.getUsername());
            ps.setString(2,user.getPassword());
            ps.setString(3,user.getPhone());
            ps.setString(4,user.getAddress());
            ps.setInt(5,user.getId());

            int rows = ps.executeUpdate();
            System.out.println("Query OK, " + rows + " rows affected");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
            System.out.println("未找到驱动");
        } catch (SQLException e) {
            e.printStackTrace();
            System.out.println("连接数据库失败");
        } finally {
            // 6.释放资源
            if (conn != null) {
                try {
                    conn.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                    System.out.println("释放连接出错");
                }
            }
            if (ps != null) {
                try {
                    ps.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public static void deleteById(Integer id){
        Connection conn = null;
        PreparedStatement ps = null;
        try {
            Class.forName("com.mysql.jdbc.Driver");
            conn = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/jdbc?useUnicode=true&characterEncoding=utf-8", "root", "");
            String sql = new StringBuffer()
                    .append(" delete from t_user ")
                    .append(" where id = ? ")
                    .toString();
            ps = conn.prepareStatement(sql);
            ps.setInt(1,id);
            int rows = ps.executeUpdate();
            System.out.println("Query OK, " + rows + " rows affected");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
            System.out.println("未找到驱动");
        } catch (SQLException e) {
            e.printStackTrace();
            System.out.println("连接数据库失败");
        } finally {
            // 6.释放资源
            if (conn != null) {
                try {
                    conn.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                    System.out.println("释放连接出错");
                }
            }
            if (ps != null) {
                try {
                    ps.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public static List<User> selectAll(){
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        List<User> users = new ArrayList<>();
        try {
            Class.forName("com.mysql.jdbc.Driver");
            conn = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/jdbc?useUnicode=true&characterEncoding=utf-8", "root", "");

            String sql = new StringBuffer()
                    .append(" select id,username,password,phone,address ")
                    .append(" from t_user ")
                    .toString();
            ps = conn.prepareStatement(sql);
            rs = ps.executeQuery();
            while(rs.next()){
                User user = new User();
                user.setId(rs.getInt(1));
                user.setUsername(rs.getString("username"));
                user.setPassword(rs.getString("password"));
                user.setPhone(rs.getString("phone"));
                user.setAddress(rs.getString("address"));
                users.add(user);
            }

        } catch (ClassNotFoundException e) {
            e.printStackTrace();
            System.out.println("未找到驱动");
        } catch (SQLException e) {
            e.printStackTrace();
            System.out.println("连接数据库失败");
        } finally {
            // 6.释放资源
            if (conn != null) {
                try {
                    conn.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                    System.out.println("释放连接出错");
                }
            }
            if (ps != null) {
                try {
                    ps.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if(rs != null){
                try {
                    rs.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
        return users;
    }

    public static User selectById(Integer id){
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        User user = null;
        try {
            Class.forName("com.mysql.jdbc.Driver");
            conn = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/jdbc?useUnicode=true&characterEncoding=utf-8", "root", "");
            String sql = new StringBuffer()
                    .append(" select id,username,password,phone,address ")
                    .append(" from t_user ")
                    .append(" where id = ? ")
                    .toString();
            ps = conn.prepareStatement(sql);
            ps.setInt(1,id);
            rs = ps.executeQuery();
            if(rs.next()){
                user = new User();
                user.setId(rs.getInt("id"));
                user.setUsername(rs.getString("username"));
                user.setPassword(rs.getString("password"));
                user.setPhone(rs.getString("phone"));
                user.setAddress(rs.getString("address"));
            }
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
            System.out.println("未找到驱动");
        } catch (SQLException e) {
            e.printStackTrace();
            System.out.println("连接数据库失败");
        } finally {
            // 6.释放资源
            if (conn != null) {
                try {
                    conn.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                    System.out.println("释放连接出错");
                }
            }
            if (ps != null) {
                try {
                    ps.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if(rs != null){
                try {
                    rs.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
        return user;
    }
}
